package com.song.utils;

import com.song.enums.FaceVerifyType;
import com.song.exception.GraceException;
import com.song.grace.result.ResponseStatusEnum;
import com.song.utils.extend.CloudServiceResource;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.iai.v20200303.IaiClient;
import com.tencentcloudapi.iai.v20200303.models.CompareFaceRequest;
import com.tencentcloudapi.iai.v20200303.models.CompareFaceResponse;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

@Component
public class FaceVerifyUtils {

    private static final Logger LOG = LoggerFactory.getLogger(FaceVerifyUtils.class);

    @Autowired
    private CloudServiceResource cloudServiceResource;

    /**
     * 腾讯云人脸对比识别
     * 发送POST请求 进行两张图的人脸对比
     * @param type
     *          0: 通过url识别，参数Url不为空；1: 通过图片base64识别，参数Image不为空
     * @param face1
     *          type为0，则传入图片url，为1则传入base64
     * @param face2
     *          type为0，则传入图片url，为1则传入base64
     * @return
     */
    public String sendPostVerifyFace(int type, String face1, String face2) throws Exception {

        String result = "";
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(cloudServiceResource.getSecretId(), cloudServiceResource.getSecretSecret());
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setConnTimeout(30); // 请求连接超时时间，单位为秒(默认60秒)
            httpProfile.setWriteTimeout(30);  // 设置写入超时时间，单位为秒(默认0秒)
            httpProfile.setReadTimeout(30);  // 设置读取超时时间，单位为秒(默认0秒)
            httpProfile.setEndpoint("iai.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            IaiClient client = new IaiClient(cred, "ap-guangzhou", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            CompareFaceRequest req = new CompareFaceRequest();
            if (type == FaceVerifyType.BASE64.type) {
                req.setImageA(face1);
                req.setImageB(face2);
            } else if (type == FaceVerifyType.IMAGE_URL.type) {
                req.setUrlA(face1);
                req.setUrlB(face2);
            } else {
                GraceException.display(ResponseStatusEnum.FACE_VERIFY_TYPE_ERROR);
            }
            // 返回的resp是一个CompareFaceResponse的实例，与请求对象对应
            CompareFaceResponse resp = client.CompareFace(req);
            // 输出json格式的字符串回包
            result = CompareFaceResponse.toJsonString(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *
     * @param type
     * @param face1
     * @param face2
     * @param targetScore
     *          目标可信度，自定义阈值
     * @return
     */
    public boolean faceVerify(int type, String face1, String face2, double targetScore) {

        String response = null;
        try {
            response = sendPostVerifyFace(type, face1, face2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> map = JsonUtils.jsonToPojo(response, Map.class);
        Object scoreStr = map.get("Score");
        Double responseScore = (Double)scoreStr;

        LOG.info("人脸对比结果：{}", responseScore);

//        System.out.println(response.toString());
//        System.out.println(map.toString());

        if (responseScore > targetScore) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     * 将图片转换为Base64
     * 将base64编码字符串解码成img图片
     * @param imgUrl
     * @return
     */
    public String getImgBase64(String imgUrl){
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgUrl);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容放到内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        return Base64.encodeBase64String(data.toByteArray());
    }

//    public static void main(String[] args) {
//        String face3 = "http://122.152.205.72:88/group1/M00/00/05/CpoxxF5MvvGAfnLXAAIHiv37wNk363.jpg";
//        String face4 = "http://122.152.205.72:88/group1/M00/00/05/CpoxxF5Mv3yAH74mAACOiTd9pO4462.jpg";
//
//        boolean result = new FaceVerifyUtils().faceVerify(FaceVerifyType.IMAGE_URL.type, face3, face4, 60);
//
//        LOG.info("人脸对比是否成功：{}", result);
//    }

}

